# rubocop:disable Naming/MethodName
module DengHaiLightTools
  module Tools
    # 灯具编辑模式
    class EditMode
      def activate
        @start = []
        @end = []
        set_text
      end

      def deactivate(view)
        view.invalidate
      end

      def onMouseMove(_flags, x, y, view)
        @end = [x, y] unless @start.empty?
        view.invalidate
      end

      def onLButtonDown(_flags, x, y, view)
        @start = [x, y] if @end.empty?
        view.invalidate
      end

      # 当键盘按键被按下时触发的事件。
      def onKeyDown(key, _repeat, _flags, _view)
        # 检查是否按下了Ctrl键，并切换旋转角度。
        toggle_angle_if_ctrl_pressed(key)
        set_text
        # 根据按下的键获取旋转轴。
        axis = get_axis_from_key(key)

        # 如果找到了对应的旋转轴，则旋转所选对象。
        rotate_selected_objects(axis) if axis
      end

      # 如果按下的是Ctrl键，切换旋转的角度。
      def toggle_angle_if_ctrl_pressed(key)
        return unless key == VK_CONTROL

        current_angle = DataManager.data['angle']
        # 根据当前的角度切换到另一个角度。
        new_angle = current_angle == 45.degrees ? 90.degrees : 45.degrees
        DataManager.data['angle'] = new_angle
      end

      # 根据按下的键返回对应的旋转轴。
      # 返回值是一个轴向量或者nil（如果按键不匹配任何已知的轴）。
      def get_axis_from_key(key)
        case key
        when VK_UP
          Z_AXIS
        when VK_LEFT
          X_AXIS
        when VK_RIGHT
          Y_AXIS
        end
      end

      # 旋转当前选中的对象。
      # 参数：axis - 旋转轴
      def rotate_selected_objects(axis)
        # 循环遍历当前选择的所有对象。
        Sketchup.active_model.selection.each do |obj|
          # 跳过非组件实例的对象。
          next unless obj.is_a?(Sketchup::ComponentInstance)

          # 获取对象的原点。
          origin = obj.transformation.origin

          # 计算旋转变换。
          rotation = Geom::Transformation.rotation(origin, axis, DataManager.data['angle'])

          # 对对象应用旋转变换。
          obj.transform!(rotation)
        end
      end

      def onLButtonUp(flags, x, y, view)
        model = Sketchup.active_model
        selection = model.selection
        pick_helper = view.pick_helper
        picked_entity = []
        # 如果用户只是简单地点击了一个点
        if @start.empty? || @end.empty? || (@start == [@end[0], @end[1]])
          pick_helper.do_pick(x, y)
          picked = pick_helper.best_picked
          picked_entity = picked if picked && DengHaiLightTools.helpers_get_attribute(picked)
        else
          # 如果用户拖动鼠标定义了一个矩形区域
          pick_helper.window_pick(@start, @end, Sketchup::PickHelper::PICK_CROSSING)
          pick_helper.all_picked.each do |obj|
            picked_entity << obj if DengHaiLightTools.helpers_get_attribute(obj)
          end
        end
        # 按下shift表示追加，否则为重新选择。
        selection.clear unless flags == 4
        # 如果有实体被选中，将其添加到选择集中

        selection.add(picked_entity) if picked_entity
        # 重置起始和结束点
        @start = []
        @end = []
        view.invalidate
      end

      def draw(view)
        edit_mode_text(view)
        set_text
        return if @start.empty? || @end.empty?

        selection_rect = [
          Geom::Point3d.new(@start[0], @start[1], 0),
          Geom::Point3d.new(@end[0], @start[1], 0),
          Geom::Point3d.new(@end[0], @end[1], 0),
          Geom::Point3d.new(@start[0], @end[1], 0)
        ]
        view.line_stipple = '-'
        view.line_width = 2
        view.drawing_color = Sketchup::Color.new(193, 25, 32)
        view.draw2d(GL_LINE_LOOP, selection_rect)
      end

      # 右键菜单
      def getMenu(menu)
        create_context_menu(menu)
      end

      # 反选(只选择灯具)
      def invert_selection
        model = Sketchup.active_model
        selection = model.selection
        all_entities = model.active_entities.to_a

        # 筛选出具有合法值的组件实例
        valid_instances = all_entities.select do |entity|
          entity.is_a?(Sketchup::ComponentInstance) && DengHaiLightTools.helpers_get_attribute(entity)
        end

        # 反选具有合法值的组件实例
        valid_instances.each do |instance|
          if selection.include?(instance)
            selection.remove(instance)
          else
            selection.add(instance)
          end
        end
      end

      # 获取所有选择集的唯一标识符
      def get_unique_identifiers(picked_entities)
        identifiers = {}

        picked_entities.each do |entity|
          attributes = DengHaiLightTools.helpers_get_attribute(entity)
          next unless attributes

          identifier = "#{attributes['light_name']}_#{attributes['channel_count']}ch"
          identifiers[identifier] ||= []
          identifiers[identifier] << entity
        end

        identifiers
      end

      # 被暂停后恢复使用
      def onResume(view)
        view.invalidate
      end

      def onSetCursor
        UI.set_cursor(UI.create_cursor("#{ICON_PATH}/mouse_edit_mode.png", 0, 0))
      end

      # 创建菜单
      def create_context_menu(menu)
        menu.add_item('反选(只有灯具)') do
          invert_selection
        end

        menu.add_item('对称复制') do
          DengHaiLightTools.copy_light
        end

        model = Sketchup.active_model
        selection = model.selection
        picked_entities = selection.to_a
        return menu if picked_entities.empty?

        menu.add_separator
        submenu = menu.add_submenu('筛选灯具')
        identifiers = get_unique_identifiers(picked_entities)
        identifiers.each do |identifier, entities|
          submenu.add_item(identifier) do
            # 4. 当选择某个子菜单时，选择所有具有相应 light_name 和 channel_count 属性的组件实例。
            selection.clear
            selection.add(entities)
          end
        end
      end

      def edit_mode_text(view)
        # 定义矩形框的四个角点
        pt1 = Geom::Point3d.new(10, 10, 0)
        pt2 = Geom::Point3d.new(150, 10, 0)
        pt3 = Geom::Point3d.new(150, 50, 0)
        pt4 = Geom::Point3d.new(10, 50, 0)

        # 绘制背景
        view.drawing_color = Sketchup::Color.new(252, 200, 14)
        view.draw2d(GL_QUADS, pt1, pt2, pt3, pt4)

        # 绘制边框
        view.line_width = 2
        view.line_stipple = '-'
        view.drawing_color = Sketchup::Color.new(193, 25, 32)
        view.draw2d(GL_LINE_LOOP, pt1, pt2, pt3, pt4)

        # 在框内居中显示“灯具编辑模式”这段文字，并设定文字大小
        text_point = Geom::Point3d.new(80, 32.5, 0) # 中心点
        options = {
          align: TextAlignCenter,
          vertical_align: TextVerticalAlignCenter,
          height: 24, # 设定文字大小为24
          color: Sketchup::Color.new(0, 0, 0)
        }
        view.draw_text(text_point, '灯具编辑模式', options)
      end

      # 设置状态栏文本
      def set_text
        DataManager.data['angle'] = 90.degrees unless DataManager.data['angle']
        @degrees = DataManager.data['angle'] * 180 / Math::PI
        Sketchup.set_status_text("本模式下仅可选择灯具，Shift加选。按方向键自轴旋转灯具；Ctrl切换旋转角度（#{@degrees.round}°）")
      end
    end
  end
end
# rubocop:enable Naming/MethodName
